
package com.lmx.persistence.service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.lmx.common.constants.ICommonConstants;
import com.lmx.common.util.CommonUtil;
import com.lmx.repoDomain.tmodel.Account;
import com.lmx.repoDomain.tmodel.DealFlow;
import com.lmx.repoDomain.tmodel.Dicttype;
import com.lmx.repoDomain.tmodel.PayRecord;
//import com.lmx.repoDomain.model.*;
import com.lmx.repoDomain.tmodel.business.User;//huibati
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;


/**
 * #{description}
 * 支付记录接口
 * @author shen
 * @version 1.00
 */
@Service
@Scope("prototype")
public class PayService<T>{
	
	private Log logger = LogFactory.getLog(this.getClass());

    @PersistenceContext
    private EntityManager em;
    
    @Autowired
    protected GenericService dslJpaService;

    /**
     * 获取支付记录列表
     * @param values
     * @return
     */
    public List<Map<String ,Object>> getPayRecordList(Map<String ,Object> values){
    	
		logger.debug("获取支付记录列表");
		
		List<Map<String ,Object>> customerPayRecordList = new ArrayList<Map<String ,Object>>();
		
		String payType = (String)values.get("payType");
		String query = "select pr from PayRecord pr where pr.payType = "+payType;
		
		//用户名
		String loginName = (String)values.get("loginName");
		if(loginName != null && !loginName.isEmpty()){
			query = query + " and pr.user.loginName like '%"+loginName+"%'";
		}
		//企业名称
		String entName = (String)values.get("entName");
		if(entName != null && !entName.isEmpty()){
			query = query + " and pr.user.entName like '%"+entName+"%'";
		}
		//姓名
		String name = (String)values.get("name");
		if(name != null && !name.isEmpty()){
			query = query + " and pr.user.name like '%"+name+"%'";
		}
		//创建时间
		String startTime = (String)values.get("startTime"); 
		String enTime = (String)values.get("enTime");
		if(startTime != null && !startTime.toString().isEmpty() && enTime != null && !enTime.toString().isEmpty()){
			try {
				Integer startInt = CommonUtil.strToIntegerTime(startTime);
				Integer endInt = CommonUtil.strToIntegerTime(enTime);
				query = query + " and pr.createTime between "+startInt+" and "+endInt;
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//支付状态
		String payStatus = (String)values.get("payStatus");
		if(payStatus != null && !payStatus.isEmpty()){
			query = query + " and pr.payStatus = "+payStatus;
		}
		query = query +" order by pr.createTime desc";
		
		Query qu = (Query) this.em.createQuery(query);
		qu.setMaxResults((int)values.get("size"));
		qu.setFirstResult((int)values.get("pageNum"));
		List resultList = qu.getResultList();
				
		for(int i = 0 ; i < resultList.size() ; i ++){
			PayRecord payRecord = (PayRecord) resultList.get(i);
			Map<String ,Object> payRecordMap = new HashMap<String, Object>();
			
			Long payRecordID = payRecord.getId();
			payRecordMap.put("payRecordID", payRecordID.toString());//支付记录id
			String loginNameStr = "";
			String entNameStr = "";
			String nameStr = "";
			String phone = "";
			Double amountBefore = 0.0;
			Double payeeBalance = 0.0;
			Double payerBalance = 0.0;
			User user = payRecord.getUser();
			if(user != null){
				loginNameStr = user.getLoginName();
				entNameStr = user.getEntName();
				nameStr = user.getName();
				phone = user.getStaffTel();
				long userID = user.getId();
				String dfQuery = "";
				if(payType.equals("1")){//充值,用户为收款方
					dfQuery = "select df from DealFlow df where df.payee.id = ?1 and df.payRecord.id = ?2";
				}else if(payType.equals("2")){//提现，用户为付款方
					dfQuery = "select df from DealFlow df where df.payer.id = ?1 and df.payRecord.id = ?2";
				}
				List dealFlowList = this.em.createQuery(dfQuery)
						.setParameter(1, userID)
						.setParameter(2, payRecordID)
						.getResultList();
				if(dealFlowList.size()>0){
					DealFlow dealFlow = (DealFlow)dealFlowList.get(0);
					amountBefore = dealFlow.getAmount();
					payeeBalance = dealFlow.getPayeeBalance();
					payerBalance = dealFlow.getPayerBalance();
				}
			}
			payRecordMap.put("loginName", loginNameStr==null?loginNameStr="":loginNameStr);//用户名
			payRecordMap.put("entName", entNameStr==null?entNameStr="":entNameStr);//企业名称
			payRecordMap.put("name", nameStr==null?nameStr="":nameStr);//真实姓名
			payRecordMap.put("phone", phone==null?phone="":phone);//手机号
			Double amount = payRecord.getAmount();
			payRecordMap.put("amount", amount==null?amount=0.0:amount);//提现金额
			payRecordMap.put("amountBefore", amountBefore==null?amountBefore=0.0:amountBefore);//提佣前金额
			payRecordMap.put("payeeBalance", payeeBalance==null?payeeBalance=0.0:payeeBalance);//收款方余额
			payRecordMap.put("payerBalance", payerBalance==null?payerBalance=0.0:payerBalance);//付款方余额
			Double platformProportion = payRecord.getPlatformProportion();
			payRecordMap.put("platformProportion", platformProportion==null?platformProportion=0.0:platformProportion);//提佣比例
			String sysAccount = payRecord.getSysAccount();
			payRecordMap.put("sysAccount", sysAccount==null?sysAccount="":sysAccount);//系统账户
			String sysAccountType = "";
			Short sysAccountTypeNum = payRecord.getSysAccountType();
			if(sysAccountTypeNum != null){
				sysAccountType = ICommonConstants.ACCOUNTTYPE.values()[sysAccountTypeNum].label();
			}
			payRecordMap.put("sysAccountType", sysAccountType);//系统账户类别
			String userAccountStr = payRecord.getUserAccount();
			payRecordMap.put("userAccount", userAccountStr==null?userAccountStr="":userAccountStr);;//用户账户
			String userAccountTypeStr = "";
			Short userAccountTypeNum = payRecord.getUserAccountType();
			if(userAccountTypeNum != null){
				userAccountTypeStr = ICommonConstants.ACCOUNTTYPE.values()[userAccountTypeNum].label();
			}
			payRecordMap.put("userAccountType", userAccountTypeStr);//用户账户类别
			String payChannel = "";
			Short payChannelNum = payRecord.getPayChannel();
			if(payChannelNum != null){
				payChannel = ICommonConstants.ACCOUNTTYPE.values()[payChannelNum].label();
			}
			payRecordMap.put("payChannel", payChannel);//支付渠道
			String payTime = "";
			Integer payTimeInt = payRecord.getPayTime();
			if(payTimeInt != null){
				payTime = CommonUtil.integetTimeForString(payTimeInt);
			}
			payRecordMap.put("payTime", payTime);//支付时间
			Short payStatusSH = payRecord.getPayStatus();
			payRecordMap.put("payStatus", payStatusSH==null?payStatusSH=3:payStatusSH);//支付状态
			String failReason = payRecord.getFailReason();
			payRecordMap.put("failReason", failReason==null?failReason="":failReason);//支付失败原因
			String createTime = "";
			Integer createTimeInt = payRecord.getCreateTime();
			if(createTimeInt != null){
				createTime = CommonUtil.integetTimeForString(createTimeInt);
			}
			payRecordMap.put("createTime", createTime);//创建时间
			String remark = payRecord.getRemark();
			payRecordMap.put("remark", remark==null?remark="":remark);//备注
			
			customerPayRecordList.add(payRecordMap);
		}
		
        return customerPayRecordList;
    }
    
    /**
     * 获取支付记录列表总条数
     * @param values
     * @return
     */
    public int getPayRecordListCount(Map<String ,Object> values){
    	
		logger.debug("获取支付记录列表总条数");
		
		String payType = (String)values.get("payType");
		String query = "select count(pr.id) from PayRecord pr where pr.payType = "+payType;
		
		//用户名
		String loginName = (String)values.get("loginName");
		if(loginName != null && !loginName.isEmpty()){
			query = query + " and pr.user.loginName like '%"+loginName+"%'";
		}
		//企业名称
		String entName = (String)values.get("entName");
		if(entName != null && !entName.isEmpty()){
			query = query + " and pr.user.entName like '%"+entName+"%'";
		}
		//姓名
		String name = (String)values.get("name");
		if(name != null && !name.isEmpty()){
			query = query + " and pr.user.name like '%"+name+"%'";
		}
		//支付日期
		String startTime = (String)values.get("startTime");
		String enTime = (String)values.get("enTime");
		if(startTime != null && !startTime.toString().isEmpty() && enTime != null && !enTime.toString().isEmpty()){
			try {
				Integer startInt = CommonUtil.strToIntegerTime(startTime);
				Integer endInt = CommonUtil.strToIntegerTime(enTime);
				query = query + " and pr.createTime between "+startInt+" and "+endInt;
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//支付状态
		String payStatus = (String)values.get("payStatus");
		if(payStatus != null && !payStatus.isEmpty()){
			query = query + " and pr.payStatus = "+payStatus;
		}
		int count = (int)(long)this.em.createQuery(query)
    			.getSingleResult();
		
        return count;
    }
    
    /**
     * 获取交易流水列表
     * @param payRecordID
     * @return
     */
    public List<Map<String ,Object>> getCustomerDealFlowList(long payRecordID){
    	
		logger.debug("获取交易流水列表");
		
		List<Map<String ,Object>> customerDealFlowList = new ArrayList<Map<String ,Object>>();
		
		String query = "select df from DealFlow df where df.payRecord.id = ?1";
		
		//获取交易流水列表
		List resultList = this.em.createQuery(query)
    			.setParameter(1, payRecordID)
    			.getResultList();
		
		for(int i = 0 ; i < resultList.size() ; i ++){
			DealFlow dealFlow = (DealFlow) resultList.get(i);
			Map<String ,Object> dealFlowMap = new HashMap<String, Object>();
			
			String payer = "";
			User payerUser = dealFlow.getPayer();
			if(payerUser != null){
				payer = payerUser.getLoginName();
			}
			dealFlowMap.put("payer", payer);//付款方
			String payee = "";
			User payeeUser = dealFlow.getPayee();
			if(payeeUser != null){
				payee = payeeUser.getLoginName();
			}
			dealFlowMap.put("payee", payee);//收款方
			Double amount = dealFlow.getAmount();
			dealFlowMap.put("amount", amount==null?amount=0.0:amount);//金额
			Double payerBalance = dealFlow.getPayerBalance();
			dealFlowMap.put("payerBalance", payerBalance==null?payerBalance=0.0:payerBalance);//付款方余额
			Double payeeBalance = dealFlow.getPayeeBalance();
			dealFlowMap.put("payeeBalance", payeeBalance==null?payeeBalance=0.0:payeeBalance);//收款方余额
			String businessType = "";
			Dicttype dicttype = dealFlow.getBusinessType();
			if(dicttype != null){
				businessType = dicttype.getTypename();
			}
			dealFlowMap.put("businessType", businessType==null?businessType="":businessType);//交易类型
			String tradeTime = "";
			Integer tradeTimeInt = dealFlow.getTradeTime();
			if(tradeTimeInt != null){
				tradeTime = CommonUtil.integetTimeForString(tradeTimeInt);
			}
			dealFlowMap.put("tradeTime", tradeTime);//交易时间
			String createTime = "";
			Integer createTimeInt = dealFlow.getCreateTime();
			if(createTimeInt != null){
				createTime = CommonUtil.integetTimeForString(createTimeInt);
			}
			dealFlowMap.put("createTime", createTime);//创建时间
			
			customerDealFlowList.add(dealFlowMap);
		}
		
        return customerDealFlowList;
    }
    
    /**
     * 客服提现，运营支付成功
     * @param payRecord
     * @return
     */
    @Transactional
    public DealFlow paySuccess(PayRecord payRecord){
    	
		logger.debug("客服提现，运营支付成功");
		
		String query = "update PayRecord pr set pr.payChannel = ?1 , pr.payTime = ?2 , pr.payStatus = ?3 where pr.id = ?4";
		Short payStatus = 1;
		//修改提现记录支付状态及支付渠道
        this.em.createQuery(query)
                .setParameter(1, payRecord.getPayChannel())
                .setParameter(2, CommonUtil.getCurrTimes())
                .setParameter(3, payStatus)//支付状态 ：1 支付完成
                .setParameter(4, payRecord.getId())
                .executeUpdate();
        payRecord = this.em.find(PayRecord.class, payRecord.getId());
        //获取该提现记录交易流水
        DealFlow dealFlow = (DealFlow) this.em.createQuery("select df from DealFlow df where df.payer.id = ?1 and df.payRecord.id = ?2")
				.setParameter(1, payRecord.getUser().getId())
				.setParameter(2, payRecord.getId())
				.getSingleResult();
        //用户id
      	long userID = payRecord.getUser().getId();
        //付款方账户信息
		Account payerAccount = (Account) this.em.createQuery("select a from Account a where a.user.id = ?1")
				.setParameter(1, userID)
				.getSingleResult();
		if(payerAccount != null){
			
			Double withdrawDeposit = payerAccount.getWithdrawDeposit();
			withdrawDeposit = (Double) (withdrawDeposit==null?withdrawDeposit=0.0:withdrawDeposit);
			long payerAccountID = payerAccount.getId();
			//修改用户总提现金额
			this.em.createQuery("update Account a set a.withdrawDeposit = ?2 ,a.updateTime = ?3 where a.id = ?4")
	            .setParameter(2, withdrawDeposit+dealFlow.getAmount())
	            .setParameter(3, CommonUtil.getCurrTimes())
	            .setParameter(4, payerAccountID)
	            .executeUpdate();
		}
		return dealFlow;
    }
    
    /**
     * 客服提现，运营支付失败
     * @param payRecord
     * @return
     */
    @Transactional
    public DealFlow payFail(PayRecord payRecord){
    	
		logger.debug("客服提现，运营支付失败");
		
		DealFlow dealFlow = new DealFlow();
        long userID = this.em.find(PayRecord.class, payRecord.getId()).getUser().getId();
        //获取该提现记录交易流水
        DealFlow result = (DealFlow) this.em.createQuery("select df from DealFlow df where df.payer.id = ?1 and df.payRecord.id = ?2")
				.setParameter(1, userID)
				.setParameter(2, payRecord.getId())
				.getSingleResult();
		if(result != null){
			//提现金额
			Double amount = result.getAmount();
			dealFlow.setAmount(amount);
			//付款方用户id
			long payer = result.getPayer().getId();
			dealFlow.setPayee(result.getPayer());//付款方变收款方
			//付款方账户信息
			Account payerAccount = (Account) this.em.createQuery("select a from Account a where a.user.id = ?1")
					.setParameter(1, payer)
					.getSingleResult();
			if(payerAccount != null){
				//付款方账户最新余额
				Double balance = payerAccount.getBalance()+amount;
				dealFlow.setPayeeBalance(balance);
				//付款方账户id
				long payerAccountID = payerAccount.getId();
				//修改付款方账户余额
				this.em.createQuery("update Account a set a.balance = ?1 ,a.updateTime = ?3 where a.id = ?4")
	                .setParameter(1, balance)
	                .setParameter(3, CommonUtil.getCurrTimes())
	                .setParameter(4, payerAccountID)
	                .executeUpdate();
			}
			//收款方用户id
			long payee = result.getPayee().getId();
			dealFlow.setPayer(result.getPayee());;//收款方变付款方
			//收款方账户信息
			List payeeAccount =  this.em.createQuery("select a from Account a where a.user.id = ?1")
					.setParameter(1, payee)
					.getResultList();
			if(payeeAccount.size()>0){
				Account account = (Account) payeeAccount.get(0);
				//收款方账户最新余额
				Double balance = account.getBalance()-amount;
				dealFlow.setPayerBalance(balance);
				//收款方账户id
				long payeeAccountID = account.getId();
				//修改收款方账户余额
				this.em.createQuery("update Account a set a.balance = ?1 ,a.updateTime = ?3 where a.id = ?4")
	                .setParameter(1, balance)
	                .setParameter(3, CommonUtil.getCurrTimes())
	                .setParameter(4, payeeAccountID)
	                .executeUpdate();
			}
			dealFlow.setPayRecord(payRecord);
			dealFlow.setTradeTime(CommonUtil.getCurrTimes());
			dealFlow.setCreateTime(CommonUtil.getCurrTimes());
			Dicttype businessType  = new Dicttype();
			Long businessTypeID = (long) 68;
			businessType.setId(businessTypeID);
			dealFlow.setBusinessType(businessType);
			//支付失败，生成交易流水
			dslJpaService.setEntityClass(DealFlow.class);
			dealFlow = (DealFlow) dslJpaService.create(dealFlow);
		}
		
		String query = "update PayRecord pr set pr.failReason = ?1 , pr.payTime = ?2 , pr.payStatus = ?3 where pr.id = ?4";
		Short payStatus = 2;
		//修改提现记录支付状态及失败原因
        this.em.createQuery(query)
                .setParameter(1, payRecord.getFailReason())
                .setParameter(2, CommonUtil.getCurrTimes())
                .setParameter(3, payStatus)//支付状态 ：2 支付失败
                .setParameter(4, payRecord.getId())
                .executeUpdate();
        
        return dealFlow;
    }
    
    /**
     * 添加用户充值记录
     * @param payRecord
     * @return
     */
    public PayRecord addPayRecord(PayRecord payRecord){
		logger.debug("用户充值");
		payRecord.setPayType((short) 1);//支付类型
		payRecord.setPayTime(CommonUtil.getCurrTimes());//支付时间
		payRecord.setPayStatus((short) 1);//支付状态
		payRecord.setCreateTime(CommonUtil.getCurrTimes());//创建时间
		dslJpaService.setEntityClass(PayRecord.class);
		payRecord = (PayRecord) dslJpaService.create(payRecord);
		return payRecord;
    }
    
    /**
     * 获取用户充值记录详情
     * @param payRecordID
     * @return
     */
    public Map<String ,Object> getPayRecord(long payRecordID ){
    	
		logger.debug("获取用户充值记录详情");
		
		dslJpaService.setEntityClass(PayRecord.class);
		PayRecord payRecord = (PayRecord) dslJpaService.findById(payRecordID);
		Map<String ,Object> payRecordMap = new HashMap<String, Object>();
			
		payRecordMap.put("payRecordID", payRecordID);//支付记录id
		String loginNameStr = "";
		String entNameStr = "";
		String nameStr = "";
		String phone = "";
		Double payeeBalance = 0.0;
		User user = payRecord.getUser();
		if(user != null){
			loginNameStr = user.getLoginName();
			entNameStr = user.getEntName();
			nameStr = user.getName();
			phone = user.getStaffTel();
			long userID = user.getId();
			List dealFlowList = this.em.createQuery("select df from DealFlow df where df.payee.id = ?1 and df.payRecord.id = ?2")
						.setParameter(1, userID)
						.setParameter(2, payRecordID)
						.getResultList();
				if(dealFlowList.size()>0){
					DealFlow dealFlow = (DealFlow)dealFlowList.get(0);
					payeeBalance = dealFlow.getPayeeBalance();
				}
			}
			payRecordMap.put("loginName", loginNameStr==null?loginNameStr="":loginNameStr);//用户名
			payRecordMap.put("entName", entNameStr==null?entNameStr="":entNameStr);//企业名称
			payRecordMap.put("name", nameStr==null?nameStr="":nameStr);//真实姓名
			payRecordMap.put("phone", phone==null?phone="":phone);//手机号
			Double amount = payRecord.getAmount();
			payRecordMap.put("amount", amount==null?amount=0.0:amount);//充值金额
			payRecordMap.put("payeeBalance", payeeBalance==null?payeeBalance=0.0:payeeBalance);//收款方余额
			String payChannel = "";
			Short payChannelNum = payRecord.getPayChannel();
			if(payChannelNum != null){
				payChannel = ICommonConstants.ACCOUNTTYPE.values()[payChannelNum].label();
			}
			payRecordMap.put("payChannel", payChannel);//支付渠道
			String payTime = "";
			Integer payTimeInt = payRecord.getPayTime();
			if(payTimeInt != null){
				payTime = CommonUtil.integetTimeForString(payTimeInt);
			}
			payRecordMap.put("payTime", payTime);//支付时间
			Short payStatusSH = payRecord.getPayStatus();
			payRecordMap.put("payStatus", payStatusSH==null?payStatusSH=3:payStatusSH);//支付状态
			String createTime = "";
			Integer createTimeInt = payRecord.getCreateTime();
			if(createTimeInt != null){
				createTime = CommonUtil.integetTimeForString(createTimeInt);
			}
			payRecordMap.put("createTime", createTime);//创建时间
		
        return payRecordMap;
    }
}
